from django.http import HttpResponse
from django.shortcuts import render, reverse
from myadmin.views import imgupload
from myadmin import models
from .TypeViews import get_type_all
import os


# Create your views here.

def index(request):
    # 获取所有的图书信息
    book_data = models.bookshop_books.objects.filter()

    # 分配数据
    content = {'book_data': book_data}
    # print(content)

    # 图片获取
    # i.bookimgs_set.first.book_img
    # print(book_data)
    return render(request, 'myadmin/books/list.html', content)


# 图书商品 添加表单
def addbook(request):
    type_date = get_type_all()
    # for i in type_date:
    #     print(i.__dict__)

    type_content = {'typelist': type_date}

    # 显示一个添加的表单
    return render(request, 'myadmin/books/add.html', type_content)


def insertbook(request):
    #  接受表单数据
    book_data = request.POST.dict()
    book_data.pop("csrfmiddlewaretoken")
    book_data.pop("typeid")
    typeid = request.POST.getlist('typeid')
    bookimg = request.FILES.get('img_url', None)

    print(book_data)
    print(typeid)
    print(bookimg)
    '''
    {'name': '数学', 'author': '李四', 'publisher': '李四', 'pub_date': '2021-12-10', 'price': '1234', 'jianjie': '123', 'content': '123'}
    ['23']
    123.jpg   
    '''

    # 检查当前是否上传图片
    # if not bookimg:
    #     return HttpResponse('<script>alert("请为图书添加至少一张封面");location.href="history.back();";</script>')

    try:
        # 根据分类ip获取分类对象
        typeobj = models.bookshop_types.objects.filter(id__in=typeid)
        # print(typeobj)

        # 创建图书书籍对象，完成添加
        obj = models.bookshop_books(**book_data)
        obj.save()
        obj.typeid.set(typeobj)

        # 图书图片管理
        img_obj = models.bookimgs()
        img_obj.bookid = obj
        img_obj.book_img = bookimg
        img_obj.save()
        # 优化：多张图片添加，jq22网站上搜索

        url = reverse(index)
        return HttpResponse('<script>alert("成功了");location.href="' + url + '";</script>')
    except:
        url = reverse(addbook)
        return HttpResponse('<script>alert("失败了");location.href="' + url + '";</script>')


def editbook(request):
    return HttpResponse('图书信息')


def updatebook(request):
    return HttpResponse('图书信息')


def delbook(request):
    return HttpResponse('图书信息')
